<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/5/7
 * Time: 16:13
 */

namespace app\api\service;


use app\common\exception\CustomException;
use app\common\service\Host;
use app\common\service\HostContact;
use app\common\service\HostLink;
use app\common\service\platform_manage\log\ServerUpdateLogService;
use app\common\service\ServerUpdate;
use app\common\service\ServerVersion;
use think\Db;
use think\exception\ValidateException;

class ProductUpgrade extends BaseService
{
    /**
     * @name 旧平台 接收新服务端地址通知旧服务端
     * @param $data
     * @return bool
     * @author wx
     * @date 2020/5/7 17:08
     */
    public function ReceiveUpgrade($data)
    {
        //验证参数
        if (!isset($data['hostkey']) || empty($data['hostkey'])) {
            throw new ValidateException('hostkey为必须参数', 422);
        }
        if (!isset($data['update_status']) || empty($data['update_status'])) {
            throw new ValidateException('update_status为必须参数', 422);
        }

        //查询host_id
        $hostContactServer = new HostContact();
        $hostInfo = $hostContactServer->findData($data['hostkey']);

        if(empty($hostInfo)){
            throw new CustomException('未找到该主机', 422);
        }

        //修改状态
        $hostServer = new Host();
        $hostServer->modify(['id' => $hostInfo['host_id'] ],
            [
                'client_update_status' => $data['update_status']
            ]);

        return true;
    }


    /**
     * @name  新平台 获取新服务端的安装包
     * @param $data
     * @return bool
     * @author wx
     * @date 2020/5/7 22:28
     */
    public function getInstallPackagePath($data)
    {
        //1. 验证同时在线下载数

        $server = new ProductUpdate();
        $online = $server->online(200);
        if(!$online){
            throw new CustomException('同时下载数量已达上限,请等待!', 422);
        }

        //2. 验证参数
        if (!isset($data['hostkey']) || empty($data['hostkey'])) {
            throw new CustomException('hostkey为必须参数', 422);
        }

        //3. 查找客户端类型windows linux
        $hostContactServer = new HostContact();
        $hostInfo = $hostContactServer->findData($data['hostkey']);

        if(empty($hostInfo)){
            throw new CustomException('未找到该主机', 422);
        }

        $hostServer = new Host();
        $host = $hostServer->findById($hostInfo['host_id']);

        if(empty($host)){
            throw new CustomException('未找到该主机', 422);
        }

        $header = request()->domain().'/';

        //4. 获取安装包地址 并算出md5值
        if($host['os'] == 1){//windows

            $path = 'static/InstallPackage/windows/Upgrade.exe';

        }elseif ($host['os'] == 2){ //linux

            $path = 'static/InstallPackage/linux/Install.sh';

        }else{
            throw new CustomException('未知系统类型', 422);
        }

        if (!file_exists($path)) {
            throw new CustomException('安装包文件不存在', 422);
        }

        $returnData = array(
            'download_url' => $header. $path,
            'hash' => md5_file($path),
            'result_url' => $header.'client/product/ResultStatus',
            'ip' => $_SERVER['SERVER_ADDR'],
            'port' => $_SERVER['SERVER_PORT']
        );

        //5. 加入下载表
        $ip = $_SERVER['REMOTE_ADDR'];//客户端ip

        $server = new ServerUpdate();
        $data_info = $server->findData(['ip' => $ip]);
        if($data_info){
            $updateData = array(
                'status' => 1,
                'last_time' => time(),
            );
            $server->modify(['id' => $data_info['id']], $updateData);
        }else{
            $addData = array(
                'ip' => $ip,
                'status' => 1,
                'last_time' => time(),
                'ctime' => time(),
            );
            $server->add($addData);
        }

        return $returnData;
    }

    /**
     * @name 执行结果返回
     * @param $data
     * @return bool
     * @author wx
     * @date 2020/5/8 14:07
     */
    public function ResultStatus($data)
    {
        //1. 验证数据
        if (isset($data['type']) && $data['type'] == 1) {
            $check_a = ['status', 'hostkey', 'type'];
        }elseif(isset($data['type']) && $data['type'] == 2){
            $check_a = ['status', 'type', 'desc', 'new_version'];
        }else{
            throw new ValidateException('参数错误', 422);
        }

        foreach ($check_a as $v)
        {
            if(!isset($data[$v]))
            {
                throw new ValidateException($v.'为必要参数', 422);
            }
        }

        //2. 查找主机信息
        $hostInfo = Db::name('host')->alias('h')
            ->join('host_contact hc', 'h.id = hc.host_id')
            ->where('hc.key', $data['hostkey'])
            ->field('h.client_version, h.os, hc.host_id, hc.ip')->find();


        if(empty($hostInfo) && $data['type'] == 1){
            throw new CustomException('未找到该主机', 422);
        }elseif (empty($hostInfo) && $data['type'] == 2) {//服务端升级
            $hostInfo['host_id'] = 0;
            $hostInfo['ip'] = $_SERVER['SERVER_ADDR'];
        }


        if($data['type'] == 1){//客户端升级

            $file = 'static/InstallPackage/install.json';
            if (file_exists($file)) {
                $clientInfo = json_decode(file_get_contents($file), true);
            }else{
                throw new CustomException('缺少必要文件', 422);
            }

            //3. 加入更新日志
            $update_server = new ServerUpdateLogService();
            $add_update_log = array(
                    'old_version' => $hostInfo['client_version'],
                    'new_version' => $clientInfo['clientVersion'],
                    'ip' => $hostInfo['ip'],
                    'host_id' => $hostInfo['host_id'],
                    'type' => $data['type'],
                    'status' => $data['status'],
                    'desc' => $clientInfo['desc'],
                    'ctime' => time()
                );
            $update_server->add($add_update_log);

        }else{
            $versionServer = new ServerVersion();
            $oldVersion = $versionServer->getServerVersion();
            $update_server = new ServerUpdateLogService();
            $add_update_log = array(
                'old_version' => $oldVersion,
                'new_version' => $data['new_version'],
                'ip' => $_SERVER['SERVER_ADDR'],
                'host_id' => 0,
                'type' => $data['type'],
                'status' => $data['status'],
                'desc' => $data['desc'],
                'ctime' => time()
            );
            $update_server->add($add_update_log);
        }

        //4. 修改客户端状态host
        $hostLinkServer = new Host();
        $hostLinkServer->modify(['id' => $hostInfo['host_id'] ], ['client_update_status' => $data['status']]);

        //5. 修改下载任务表
        $server = new ServerUpdate();
        $server->modify(['ip' => $hostInfo['ip']], ['status' => $data['status']]);

        //6.更新版本
        if($data['type'] == 2){//服务端
            $versionServer = new ServerVersion();
            $versionServer->setServerVersion($data['new_version']);
        }else{//客户端修改成功
            if ($data['status'] == 4) {
                $hostServer = new Host();
                $hostServer->modify(['id' => $hostInfo['host_id'] ],
                    [
                        'client_version' => $clientInfo['clientVersion'],
                        'client_update_status' => $data['status']
                    ]);
            }

        }
    }
}